<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { getShoeById } from '@/apis/shoes.js'
import {addCart, getCart} from "@/apis/cart.js";
import {ElMessage} from "element-plus";
const route = useRoute()

const shoe = ref({})
const selectedSize = ref(null)

// 获取鞋子详情
const getShoeDetail = async () => {
  try {
    const res = await getShoeById(route.params.id)
    shoe.value = res.data
    selectedSize.value = shoe.value.sizes[0] // 默认选择第一个尺码
  } catch (error) {
    console.error('获取鞋子详情失败:', error)
  }
}

// 加入购物车
const addToCart = () => {
  if (!selectedSize.value) {
    alert('请选择尺码')
    return
  }
  // 构造要加入购物车的商品对象
  // 调用方法添加到购物车
  addCart(shoe.value.id,selectedSize.value)
  ElMessage.success('已添加到购物车')
}

onMounted(() => {
  getShoeDetail()
})
</script>


<template>
  <div class="shoe-detail">
    <div class="detail-container">
      <!-- 左侧图片 -->
      <div class="image-section">
        <img :src="shoe.image" alt="Shoe Image" />
      </div>

      <!-- 右侧信息 -->
      <div class="info-section">
        <h2>{{ shoe.name }}</h2>
        <p>颜色: {{ shoe.color }}</p>
        <p>价格: <strong>¥{{ shoe.price}}</strong></p>
        <p>库存: {{ shoe.number }}</p>
        <p>描述: {{ shoe.description }}</p>

        <!-- 尺码选择 -->
        <div class="size-select">
          <label>选择尺码：</label>
          <select v-model="selectedSize">
            <option v-for="size in shoe.sizes" :key="size" :value="size">
              {{ size }}
            </option>
          </select>
        </div>

        <!-- 加入购物车按钮 -->
        <button class="add-to-cart-btn" @click="addToCart">加入购物车</button>
      </div>
    </div>
  </div>
</template>


<style scoped lang="scss">
.shoe-detail {
  padding: 40px;
  background-color: #f9f9f9;
}

.detail-container {
  display: flex;
  gap: 40px;
  max-width: 1000px;
  margin: 0 auto;
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-section img {
  width: 100%;
  max-width: 400px;
  height: auto;
  border-radius: 8px;
}

.info-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  h2 {
    color: #333;
  }

  p {
    margin: 10px 0;
    color: #555;
  }

  .size-select {
    margin: 20px 0;
  }

  .add-to-cart-btn {
    align-self: flex-start;
    background-color: #d4a373;
    color: #fff;
    border: none;
    padding: 12px 24px;
    font-size: 16px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;

    &:hover {
      background-color: #c29469;
    }
  }
}
</style>
